package mhuu.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketService {
	
	public static String sendBytesToHostPort(String host,int port,byte[] bytes) throws Exception {
		Socket socket=new Socket(host, port);
		OutputStream outputStream=socket.getOutputStream();
		outputStream.write(bytes);
		outputStream.flush();
		//outputStream.close();
		InputStream in=socket.getInputStream();
		BufferedReader br=new BufferedReader(new  InputStreamReader(in,"utf-8"));
		String header="";
		int contentLength=0;
		String body="";
		while(true){
			String line=br.readLine();
			if (line==null) {
				break;
			}
			header=header+line+"\n";
			if ("".equals(line)) {
				break;
			}
			if (line.contains("Content-Length")) {
				String length=line.split(":")[1];
				//contentLength=Integer.valueOf(length.trim());
			}
		}
		System.out.println("contentLength="+contentLength);
		if (contentLength!=0) {
			byte[] bodyBytes=new byte[contentLength-10];
			
			in.read(bodyBytes);
			body=new String(bodyBytes,"utf-8");
			//System.err.println(body);
		}else {
			String line=null;
			while((line=br.readLine())!=null){ 
				body=body+line+"\n"; 
			}
		}
		socket.close();	
		return header+body;
	}
	public static void main(String[] args) throws Exception{
		String bstr="GET / HTTP/1.0\n\n";
		byte[] b=bstr.getBytes();
		String str=sendBytesToHostPort("t9cloud.com",8080,b);
		System.out.print(str);
	}
	
}
